using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AdminSG3L.Domain.Entities;
using AdminSG3L.Domain.Repositories;
using AdminSG3L.Infrastructure.Repositories;
using AdminSG3L.Infrastructure.Data;
using AdminSG3L.Infrastructure.Services;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace AdminSG3L.Infrastructure;

public static class ServiceCollectionExtenstion
{
    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration, string databaseType = "Postgres")
    {
        switch (databaseType.ToLower())
        {
            case "mysql":
                var mySqlConnectionString = configuration.GetConnectionString("Mysql");
                services.AddDbContext<AdminDbContext>(x =>
                {
                    x.UseMySql(mySqlConnectionString, ServerVersion.AutoDetect(mySqlConnectionString));
                });
                break;
            case "postgres":
            default:
                var pgConnectionString = configuration.GetConnectionString("Postgres");
                services.AddDbContext<AdminDbContext>(x =>
                {
                    x.UseNpgsql(pgConnectionString);
                });
                break;
        }

        services.AddScoped(typeof(IRepository<>), typeof(EFRepository<>));

        // 注册系统初始化服务
        services.AddScoped<SystemInitializationService>();

        return services;
    }
}

public class LogCleanupService : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;

    public LogCleanupService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var now = DateTime.Now;
            // 计算下一个周日凌晨2点
            var next = now.AddDays((7 - (int)now.DayOfWeek) % 7).Date.AddHours(2);
            var delay = next - now;
            await Task.Delay(delay, stoppingToken);

            using (var scope = _serviceProvider.CreateScope())
            {
                var db = scope.ServiceProvider.GetRequiredService<AdminDbContext>();
                await db.Database.ExecuteSqlRawAsync("TRUNCATE TABLE \"AppLogs\";", cancellationToken: stoppingToken);
            }
        }
    }
}